package com.ydy.user.service.impl;

import com.ydy.common.constant.Constant;
import com.ydy.common.model.*;
import com.ydy.common.util.JsonUtil;
import com.ydy.common.util.RedisUtil;
import com.ydy.user.mapper.UserMapper;
import com.ydy.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByName(String name) {
        User user = userMapper.getUserByName(name);
        if(user != null){
            //查询角色
            Set<Role> roles = userMapper.getRoleByUserCode(user.getUserCode());
            if(!CollectionUtils.isEmpty(roles)){
                for (Role role : roles) {
                    //查询权限
                    Set<Permissions> permissions =
                            userMapper.getPermissionsByRoleCode(role.getRoleCode());
                    role.setPermissions(permissions);
                }
                user.setRoles(roles);
            }
            RedisUtil redisUtil = new RedisUtil(redisTemplate);
            String headPortraitUrl = String.valueOf(redisUtil.get(Constant.HEAD_PORTRAIT_URL));
            user.setHeadPortrait(headPortraitUrl + user.getHeadPortrait());
        }
        return user;
    }

    @Override
    public void setUserInfoToRedis(User user, String token) {

        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        Set<Permissions> permissions = new LinkedHashSet<>();
        if(user.getRoles() != null){
            user.getRoles().forEach(role->{
                permissions.addAll(role.getPermissions());
            });
        }

        Set<String> permissionList = permissions.stream().map(Permissions::getPermissionUrl).collect(Collectors.toSet());

        //获得时间
        Long timeOutTime = Long.valueOf(String.valueOf(redisUtil.get(Constant.REDIS_TIMEOUT_TIME)));

        String userCode = user.getUserCode();
        redisUtil.set("token:" + userCode + token,token, timeOutTime);
        redisUtil.set("permission:" + userCode + token, JsonUtil.getJson(permissionList),timeOutTime);

        LOGGER.info("token:{},permissions:{}",token,permissionList);
    }

    @Override
    public List<Menu> queryUserMenus(String userCode) {
        List<Menu> menuList =  userMapper.queryUserMenus(userCode);
        //一级菜单
        List<Menu> firstMenu = menuList.stream().filter(v ->v.getMenuParentCode().equals("0")).collect(Collectors.toList());
        //二级菜单
        List<Menu> secondMenu = menuList.stream().filter(v ->!v.getMenuParentCode().equals("0")).collect(Collectors.toList());
        firstMenu.forEach(fv ->{
            Set<Menu> second = new LinkedHashSet<>();
            secondMenu.forEach(sv ->{
                if(fv.getMenuCode().equals(sv.getMenuParentCode())){
                    second.add(sv);
                }
            });
            fv.setChildren(second);
        });

        return firstMenu;
    }

    @Override
    public void reLoadRedisCaChe() {
        List<Dict> dictList = userMapper.queryDictList();
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        dictList.forEach(dict -> {
            String dictType = dict.getType();
            String dictValue = dict.getValue();
            String key = Constant.REDIS_PREFIX + dictType;
            redisUtil.set(key,dictValue);
        });
    }

    @Override
    public String getWebSocketUrl() {
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        return String.valueOf(redisUtil.get(Constant.WEB_SOCKET_URL));
    }
}
